package chris.delayMessage;

import chris.ConFactory;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * DelaySend
 *
 * @author nanxin.chen
 * @since 2017/8/1
 */
public class DelaySend {

    public static final String queueName    = "delay-queue";
    public static final String exchangeName = "delay-exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory cf = ConFactory.getConnectionFactory();

        Connection con = cf.newConnection();
        Channel channel = con.createChannel();

        Map<String, Object> params = new HashMap<>();
        params.put("x-delay-type", "direct");
        channel.exchangeDeclare(exchangeName, "x-delayed-message", false, false, params);

        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, "");

        int delayMs = 5000;
        String msg1 = "delay message " + delayMs;
        Map<String, Object> headers = new HashMap<>();
        headers.put("x-delay", delayMs);
        AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().headers(headers).build();
        channel.basicPublish(exchangeName, "", props, msg1.getBytes("utf-8"));
        System.out.println("publish delay msg with delay " + delayMs);

        delayMs = 1000;
        String msg2 = "delay message " + delayMs;
        Map<String, Object> headers2 = new HashMap<>();
        headers.put("x-delay", delayMs);
        AMQP.BasicProperties props2 = new AMQP.BasicProperties.Builder().headers(headers2).build();
        channel.basicPublish(exchangeName, "", props2, msg2.getBytes("utf-8"));
        System.out.println("publish delay msg with delay " + delayMs);

        channel.close();
        con.close();
    }

}
